'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
const collection = db.collection('leaderboard');
exports.main = async (event, context) => {
	const {
		userId,
		subjectName,
		value
	} = event;

	// 验证科目字段是否有效
	const validSubjects = ['chineseFirst', 'chineseSecond', 'chineseThird', 'chineseFourth', 'chineseFifth',
		'mathFirst', 'mathSecond', 'mathThird', 'mathFourth', 'mathFifth', 'englishFirst', 'englishSecond',
		'englishThird', 'englishFourth', 'englishFifth'
	];
	if (!subjectName || !userId || value === undefined || !validSubjects.includes(subjectName)) {
		return {
			errCode: -1,
			errMsg: '缺少必要参数'
		};
	}

	try {
		const currentTime = Date.now();
		// 查找是否已有记录
		const {
			data: userList
		} = await collection.where({
			userId: userId
		}).get();

		let result;
		if (userList && userList.length > 0) {
			let userData = {
				updateTime: currentTime,
				[subjectName]: value
			};
			// 更新现有记录
			result = await collection
				.doc(userList[0]._id)
				.update(userData);
		} else {
			// 创建新记录
			let userData = {
				createTime: currentTime,
				userId:userId,
				[subjectName]: value
			};
			result = await collection.add(userData);
		}

		return {
			errCode: 0,
			errMsg: '更新成功',
			data: result
		};
	} catch {
		return {
			errCode: -1,
			errMsg: '服务器错误',
		};
	}
};